import time

import allure
import selenium.webdriver.support.ui as ui
from selenium import webdriver

public = "https://dohko.login.internal.tiaofangzi.com/login?redirectURL=http%3A%2F%2Fpublic-mis.tiaofangzi.com"
dohko = "https://dohko.login.internal.tiaofangzi.com/login?redirectURL=http%3A%2F%2Fdohko.mis.tiaofangzi.com?redirectURL=http%3A%2F%2Fdohko.mis.tiaofangzi.com"
sales = "https://dohko-fe-mis-sales.tiaofangzi.com/#/"
support = "http://dohko-fe-mis-support.tiaofangzi.com/#/"

@allure.step("创建浏览器登录用户返回浏览器操作对象")
def user_login():
    options = webdriver.ChromeOptions()
    prefs = {
        'profile.default_content_setting_values': {
            'notifications': 2
        }
    }
    options.add_experimental_option('prefs', prefs)
    browser = webdriver.Chrome(chrome_options=options)
    browser.get(public)
    # browser.maximize_window()
    print("当前使用的浏览器是：", browser.name)  # 打印当前使用的浏览器名称
    print("当前网页title是：", browser.title)  # 打印页面title)
    time.sleep(1)

    wait = ui.WebDriverWait(browser, 10)
    wait.until(lambda browser: browser.find_element_by_xpath('//*[@id="react-tabs-2"]/span').is_displayed())
    browser.find_element_by_xpath('//*[@id="react-tabs-2"]/span').click()
    userName = browser.find_element_by_xpath('//*[@id="login-section"]/div/form/div[1]/div/span/input[1]')
    userName.send_keys('13521653526')

    browser.find_element_by_xpath('//*[@id="login-section"]/div/form/div[2]/div/div/div[1]/span/input').click()
    password = browser.find_element_by_xpath('//*[@id="login-section"]/div/form/div[2]/div/div/div[1]/span/input')
    password.send_keys('000000')

    browser.find_element_by_id('loginBtn').click()
    time.sleep(3)  # 等待页面加载，后期改成软等待
    return browser


def close_tab(wait, browser):
    try:
        wait.until(lambda browser: browser.find_element_by_xpath(
            '/html/body/div[1]/section/section/section/main/div[1]/div/div[1]/div[2]/div/div/div/div[1]/div[2]/div/i').is_displayed())
        browser.find_element_by_xpath(
            '/html/body/div[1]/section/section/section/main/div[1]/div/div[1]/div[2]/div/div/div/div[1]/div[2]/div/i').click()
    except:
        print("无法关闭tab，尝试再次关闭")
        wait.until(lambda browser: browser.find_element_by_xpath(
            '/html/body/div[1]/section/section/section/main/div[1]/div/div[1]/div[2]/div/div/div/div[1]/div[2]/div/i').is_displayed())
        browser.find_element_by_xpath(
            '/html/body/div[1]/section/section/section/main/div[1]/div/div[1]/div[2]/div/div/div/div[1]/div[2]/div/i').click()

def wait_until(wait, browser, element):
    wait.until(lambda browser: browser.find_element_by_xpath(
        element).is_displayed())
    browser.find_element_by_xpath(element).click()


if __name__ == '__main__':
    print('被导入时')